package com.hugang.newfeature.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * java内置的四大核心函数式接口
 * <p>
 * 消费型接口 Consumer<T>   void accept(T t)
 * 供给型接口 Supplier<T>   T get()
 * 函数型接口 Function<T,R> R apply(T t)
 * 断定型接口 Predicate<T>  boolean test(T t)
 *
 * @author hg
 * @date 2020/6/24 17:19
 */
public class LambdaTest2 {

    /**
     * 消费型接口Consumer<T>
     */
    @Test
    public void test1() {
        happyTime(400, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("消费了" + aDouble + "元");
            }
        });

        System.out.println("************");
        happyTime(500, d -> System.out.println("消费了" + d + "元"));
    }

    public void happyTime(double money, Consumer<Double> con) {
        con.accept(money);
    }

    /**
     * 断定型接口 Predicate<T>
     */
    @Test
    public void test2() {
        List<String> list = Arrays.asList("北京", "南京", "天津", "东京", "西京", "普京");
        List<String> list1 = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });

        System.out.println(list1);
        System.out.println("*****************");
        List<String> list2 = filterString(list, s -> s.contains("天"));
        System.out.println(list2);
    }

    /**
     * 根据给定的规则，过滤集合中的字符串。此规则由Predicate的实现类重写的test()方法决定
     *
     * @param list
     * @param pre
     * @return
     */
    public List<String> filterString(List<String> list, Predicate<String> pre) {
        ArrayList<String> returnList = new ArrayList<>();
        for (String s : list) {
            if (pre.test(s)) {
                returnList.add(s);
            }
        }
        return returnList;
    }
}
